<script setup lang="ts">
import {UploadFilled} from "@element-plus/icons-vue";
import type {UploadUserFile} from "element-plus";
import { useMessage } from '@/hooks/web/useMessage'
import {useUploadToWebDisk} from "@/views/ai/webdisk/upload";
import {WebDiskFileApi} from "@/api/ai/webdiskfile";
import { ref, inject } from 'vue';

const props = defineProps({
  dirId:String,
  spaceId:String,
});
// 提供默认值'0'防止useFlow为undefined
const useFlow = inject<string | undefined>('useFlow', '0');
const emits = defineEmits<{
  (e:'ok'):void
}>();
const message = useMessage() // 消息弹窗
const { uploadUrl, httpRequest } = useUploadToWebDisk( (url:string,type:string,name:string)=>{
  WebDiskFileApi.createWebDiskFile({
    url:url,
    mediaType:type,
    spaceId:props.spaceId,
    dirId:props.dirId,
    fileName: name,
    analysis:'not'
  }).then(()=>{
    ElMessage.success("上传成功")
    emits("ok")
  })
})
const show=ref(false);
const open=async (b:boolean)=>{
  show.value=b;
  fileList.value=[]
  console.log('open')
}
const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)
const fileList = ref<UploadUserFile[]>([])
const uploadingCount=ref(0)
// 支持的文件类型和大小限制
const supportedFileTypes = [
  'TXT',
  'MARKDOWN',
  'MDX',
  'PDF',
  'HTML',
  'XLSX',
  'XLS',
  'DOC',
  'DOCX',
  'CSV',
  'EML',
  'MSG',
  'PPTX',
  'XML',
  'EPUB',
  'PPT',
  'MD',
  'HTM',
  'MP4',
  'WEBM',
  'MOV',
  'PNG',
  'JPEG',
  'JPG',
]
const maxFileSize = 500
const allowedExtensions = supportedFileTypes.map((ext) => ext.toLowerCase()) // 小写的扩展名列表
const beforeUpload = (file: any) => {
  // 1.1 检查文件扩展名 (仅当useFlow为1时进行格式限制)
  if (useFlow === '1') {
    const fileName = file.name.toLowerCase()
    const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1)
    if (!allowedExtensions.includes(fileExtension)) {
      message.error('不支持的文件类型！')
      return false
    }
  }
  
  // 1.2 检查文件大小
  if (!(file.size / 1024 / 1024 < maxFileSize)) {
    message.error(`文件大小不能超过 ${maxFileSize} MB！`)
    return false
  }

  // 2. 增加上传中的文件计数
  uploadingCount.value++
  return true
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="show" title="批量上传文件" width="800">
    <el-upload
      class="upload-demo"
      drag
      :action="uploadUrl"
      :http-request="httpRequest"
      v-model:file-list="fileList"
      :auto-upload="true"
      multiple
      :on-error="onUploadError"
      :before-upload="beforeUpload"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text"> 拖到文件 <em>或者点击选择文件文件</em> </div>
      <template #tip>
        <div class="el-upload__tip">
          <div> 最大支持{{ maxFileSize }}MB </div>
          <div v-if="useFlow === '1'"> 支持格式: {{ allowedExtensions.join(',') }} </div>
        </div>
      </template>
    </el-upload>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
